package logic

import (
	"context"
	"time"

	"mall/common/errorx"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendUpdateMenuLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendUpdateMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendUpdateMenuLogic {
	return &BackendUpdateMenuLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendUpdateMenuLogic) BackendUpdateMenu(in *backend.UpdateMenuRequest) (*backend.UpdateMenuResponse, error) {
	if in.Id == 0 {
		return nil, errorx.Status(errorx.ERROR_MENU_ID_REQUIRED, "")
	}

	var columns []string = []string{model.BackendMenuColumns.MenuID}
	if len(in.PermIds) > 0 {
		menu, err := l.svcCtx.BackendMenu.FindOne(l.ctx, in.Id, columns)
		if err != nil {
			return nil, err
		}

		perms, _, err := l.svcCtx.BackendPermission.GetList(l.ctx, model.M{
			"ids":                                 in.PermIds,
			"select":                              ",",
			model.BackendPermissionColumns.Status: 1,
		}, -1)
		if err != nil {
			return nil, err
		}

		err = l.svcCtx.BackendMenu.SetPerms(l.ctx, menu, perms)
		if err != nil {
			return nil, err
		}
	} else {
		var pageSize int64 = 2
		menuList, _, err := l.svcCtx.BackendMenu.GetList(l.ctx, model.M{
			model.BackendMenuColumns.Name: in.Name,
			"pageSize":                    pageSize,
			"select":                      ",",
		}, -1)
		if err != nil {
			return nil, err
		}
		count := len(menuList)
		if count > 1 {
			return nil, errorx.Status(errorx.ERROR_MENU_NAME_EXISTS, "")
		}
		if count == 1 && menuList[0].MenuID != uint64(in.Id) {
			return nil, errorx.Status(errorx.ERROR_MENU_NAME_EXISTS, "")
		}

		var menu model.BackendMenu
		menu.MenuID = uint64(in.Id)
		menu.Name = in.Name
		menu.ParentID = uint64(in.Pid)
		menu.Icon = in.Icon
		menu.Path = in.Path
		menu.API = in.Api
		menu.URL = in.Url
		menu.Type = uint8(in.Type)
		menu.Status = uint8(in.Status)
		menu.DelStatus = uint8(in.Status)
		menu.MenuOrder = uint(in.MenuOrder)
		menu.LastUpdatedBy = uint64(in.UpdatedBy)
		menu.UpdatedAt = time.Now()
		_, err = l.svcCtx.BackendMenu.Update(l.ctx, &menu)
		if err != nil {
			return nil, err
		}
	}

	return &backend.UpdateMenuResponse{}, nil
}
